package com.iot08.api.service;

import com.alibaba.fastjson.JSONArray;
import com.iot08.api.constant.Constant;
import com.iot08.api.utils.request.ParamHandle;
import com.iot08.api.vo.request.AdupdateReqVO;
import com.iot08.api.vo.request.GetNotificationReqVO;
import com.iot08.api.vo.request.base.BaseAccountReqVO;
import com.iot08.common.constant.CacheEnum;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.app.Account;
import com.iot08.common.entity.app.DeviceNotification;
import com.iot08.common.entity.app.OpenidConfig;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2020/11/20 14:54
 */
@Slf4j
@Service
public class DeviceNotificationService extends BaseService<DeviceNotification> {

    @Resource
    private AccountService accountService;


    /**
     * 创建通知数据
     * @param deviceNotification
     * @time: 3/2/22 4:13 PM
     * @author: Weichao
     * @version 1.0
     */
    public String createNewNotification(DeviceNotification deviceNotification){
        deviceNotification.setTime(DateUtil.nowTimestampToLong());
        deviceNotification.setExpiryAt(DateUtil.getSystemExpiryAt());
        deviceNotification = this.save(deviceNotification);
        return deviceNotification.getId();
    }
    /**
     * 获取通知数据
     *
     * @param vo
     * @time: 2020/11/14 14:21
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap list(GetNotificationReqVO vo) {
        Account account = accountService.findById(vo.getOpenid());
        if (account == null) {
            log.info("Account is null. params={}", vo.toString());
            return ResponseMap.fail(ResponseEnum.STATUS2000.getCode(), ResponseEnum.STATUS2000.getMsg());
        }
        Document query = new Document();
        //参数query处理
        ParamHandle.queryParamHandle(query, vo.getQuery());
        Double time = account.getDeleteNotificationtime();
        if (time == null) {
            time = account.getTimestamp() == null ? 0 : account.getTimestamp();
        }
        // 增加上 查询条件, 查询 t字段 > deleteNotificationtime 字后的数据
        query.put("t", new Document().append("$gt", time));
        JSONArray orArr = JSONArray.parseArray(String.format("[{\"accept_user\":\"all\"},{\"openid\":\"%s\"}]", vo.getOpenid()));
        query.put("$or", orArr);
        List<Document> messagesList = new ArrayList<>();
        FindIterable<Document> document = this.findDoc(query, Filters.eq("t", -1), 0, vo.getNum());
        Long t = null;
        for (Document doc : document) {
            if (!StringUtil.isNumeric(doc.get("t"))) {
                continue;
            }
            Object object_T = doc.get("t");
            if (object_T instanceof Double) {
                t = Double.valueOf(doc.get("t").toString()).longValue();
            }else{
                t = Long.parseLong(doc.get("t").toString());
            }
            doc.put("id", doc.get("_id").toString());
            doc.put("timestamp", t);
            doc.put("type", doc.get("T"));
            doc.put("imei", doc.get("i"));

            doc.remove("_id");
            doc.remove("i");
            doc.remove("t");
            doc.remove("T");
            doc.remove("createTime");
            messagesList.add(doc);
        }
//        //加上 已发布状态的
//        query.put("status", 1);
//        //query.put("openid", vo.getOpenid());
//        List<Document> messagesList = new ArrayList<>();
//        FindIterable<Document> document = this.findDoc(query, Filters.eq("t", -1), 0, vo.getNum());
//        List<String> showMsgIdList = new ArrayList<>();
//        if (StringUtil.isNotBlank(vo.getOpenid())) {
//            //设置读取时间
//            String key = String.format("%s%s", vo.getOpenid(), CacheEnum.READ_SYS_MSG_TIME.getKey());
//            redisFilterService.set(key, String.valueOf(System.currentTimeMillis() / 1000));
//            OpenidConfig openidConfig = openidConfigService.findById(vo.getOpenid());
//            if (openidConfig != null && openidConfig.getShowMsgIdList() != null) {
//                showMsgIdList.addAll(openidConfig.getShowMsgIdList());
//            }
//        }
//        Long t = null;
//        for (Document doc : document) {
//            if (!StringUtil.isNumeric(doc.get("t"))) {
//                continue;
//            }
//            t = Long.parseLong(doc.get("t").toString());
//            // 时间是用户 getDeleteNotificationtime 之后的时间, 同时获取的信息也要小于当前的时间的
//            if (t > time.longValue()
//                    && t < DateUtil.nowTimestampToDouble()) {
//                //判断是 单个用户(有openid)||部分用户("group"的标识)||全部用户("all" 和 ""的标识) 的消息
//                if ((StringUtil.isNotBlank(doc.get("openId")) && !"all".equals(doc.get("accept_user")) && !doc.get("openId").equals(vo.getOpenid()))
//                        || ("group".equals(doc.get("accept_user")) && !showMsgIdList.contains(doc.get("_id").toString()))) {
//                    continue;
//                }
//                if (StringUtil.isNotBlank(doc.getString("i"))) {
//                    doc.put("imei", doc.getString("i"));
//                    doc.remove("i");
//                }
//                doc.put("id", doc.get("_id").toString());
//                doc.put("timestamp", t);
//                doc.put("type", doc.get("T"));
//                if (Const.INT_1.equals(doc.getInteger("skip_type"))) {
//                    doc.put("contentType", "web");
//                } else if (new Integer(2).equals(doc.getInteger("skip_type"))) {
//                    doc.put("contentType", "small_program");
//                    doc.put("smallprogram_id", doc.get("small_program_id"));
//                    doc.put("smallprogram_path", doc.get("small_program_path"));
//                    doc.remove("small_program_id");
//                    doc.remove("small_program_path");
//                } else if (new Integer(3).equals(doc.getInteger("skip_type"))) {
//                    doc.put("contentType", "web_jump_WXGZ");
//                    doc.put("jump_Tips_Words", doc.get("jump_tips_words"));
//                    doc.remove("jump_tips_words");
//                } else if (new Integer(4).equals(doc.getInteger("skip_type"))) {
//                    doc.put("contentType", "ADSDK_jump");
//                    doc.put("SDKType", doc.get("advert_firm"));
//                    doc.remove("advert_firm");
//                }
//                doc.remove("_id");
//                doc.remove("t");
//                doc.remove("T");
//                doc.remove("createTime");
//                messagesList.add(doc);
//            }
//        }
        ResponseMap res = ResponseMap.success();
        res.put("messages", messagesList);
        return res;
    }

    /**
     * 删除通知数据
     *
     * @param vo
     * @time: 2020/11/20 14:27
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap delByOpenid(BaseAccountReqVO vo) {
        //更新删除时间
        Update update = new Update();
        update.set("deleteNotificationtime", DateUtil.nowTimestampToDouble());
        accountService.updateById(vo.getOpenid(), update);
        return ResponseMap.success();
    }

    /**
     * 上传广告资源信息接口
     *
     * @param vo
     * @time: 2021/1/6 10:22
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap adupdate(AdupdateReqVO vo) {
        if (vo.getTimestamp() == null) {
            vo.setTimestamp(System.currentTimeMillis() / 1000);
        }
        String authKey = DigestUtils.md5Hex(Constant.YQAD_UPDATE + vo.getTimestamp()).toUpperCase();
        if (!authKey.equals(vo.getAuthKey())) {
            return ResponseMap.fail(ResponseEnum.STATUS403.getCode(), "认证失败.Key值错误");
        }
        DeviceNotification dn = new DeviceNotification();
        dn.setMsgid(vo.getMsgid() == null ? "" : vo.getMsgid());
        dn.setType("YXNew");
        dn.setJumptype(vo.getJumptype() + "");
        dn.setTitle(vo.getMsgTitle());
        dn.setContent(vo.getMsgContent());
        dn.setCreateTime(new Date());
        if (!Const.INT_1.equals(vo.getJumptype())) {
            //新闻才有, 任务没有这东西
            dn.setDirectoryid(vo.getDirectoryid());
            dn.setUrl(vo.getMsgUrl());
        }
        dn.setExpiryAt(DateUtil.getSystemExpiryAt());
        dn.setTime(System.currentTimeMillis() / 1000);
        //保存
        this.save(dn);
        return ResponseMap.success();
    }
}
